<?php

class Cache{
	/**
	 *
	 * @var Zend_Cache_Core
	 */
	public static $instance;
	/**
	 * 
	 *
	 * @var MemcacheGroup
	 */
	public static $memc;
	
	/**
	 * 
	 *
	 * @return Zend_Cache_Core
	 */
	public static function getInstance(){
		if(empty(self::$instance)){
			/*
			self::$memc = MemcacheGroup::getInstance2($_SERVER['config']['memcache']);
			self::$instance = new Zend_Cache_Core(
				array(
				'lifetime' => 1800,                   
			    'automatic_serialization' => true  
				)
			);
			$cache_backend = new Zend_Cache_Backend_Memcached();
			$cache_backend->_memcache = self::$memc;
			self::$instance->setBackend($cache_backend);
			*/
			self::$instance = Mem::getInstance($_SERVER['config']['memcache']);			
		}
		return self::$instance;
	}
	
	public static function cacheFunction($func, $arguments, $refresh=false, $life=1800){
		$key = self::makeFunctionKey($func, $arguments);
		if($refresh){
//			Log::getInstance()->log("##################remove: ".$key, LOG_INFO);
			self::getInstance()->remove($key);
		}
		if(!($ret=self::getInstance()->load($key)) and ($ret===null or $ret===false)){
			$ret = call_user_func_array($func, $arguments);
			if($ret!==null){
				$flag = self::getInstance()->save($ret, $key, array(), $life);
			}
		}
		return $ret;
	}
	
	public static function cleanFunctionCache($func, $arguments){
		$key = self::makeFunctionKey($func, $arguments);
		return self::getInstance()->remove($key);
	}
	
	public static function makeFunctionKey($func, $arguments){
		$func_str = '';
		if(is_array($func)){
			$func_str = get_class($func[0]).'->'.$func[1]."(".json_encode($arguments).")";
		}else{
			$func_str = $func."(".json_encode($arguments).")";
		}
//		echo $func_str."\n";
		$key = "SNS_FUNC_".md5($func_str);
		return $key;
	}
}